package com.gupao.jly521.action.mvc;

import com.gupao.jly521.action.mvc.action.IController;
import com.gupao.jly521.action.mvc.action.OrderAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jly
 * @date 2018/9/3  15:44
 */
public class ServletDispatcher {

    List<Handler> handlerList = new ArrayList<>();

    public ServletDispatcher() throws Exception {
        handlerList.add(new Handler()
                .setController(new OrderAction())
                .sethMethod(OrderAction.class.getMethod("orderJob",new Class[]{String.class}))
                .setUri("/delegate/orderJob"));
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
        doService(request,response);
    }

    private void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String uri = request.getRequestURI();
        Handler handler = null;
        for (Handler handlerTmp : handlerList) {
            if(uri.contains(handlerTmp.getUri())){
                handler=handlerTmp;
                break;
            }
        }
        Method method = handler.gethMethod();
        Object obj = method.invoke(handler.getController());
        System.out.println("end");
        response.getWriter().write(obj.toString());
    }

    class Handler{

        IController controller;

        Method hMethod;

        String uri;

        public IController getController() {
            return controller;
        }

        public Handler setController(IController controller) {
            this.controller = controller;
            return this;
        }

        public Method gethMethod() {
            return hMethod;
        }

        public Handler sethMethod(Method hMethod) {
            this.hMethod = hMethod;
            return this;
        }

        public String getUri() {
            return uri;
        }

        public Handler setUri(String uri) {
            this.uri = uri;
            return this;
        }
    }
}
